<?php

/**
 * 
 * @author Administrator
 *
 */
class ServerApplyService extends Service{

    public static function indexHeader(){
        $header = array(
            'id'            => array('text' => '服务器ID', 'width' => '90px'),
            'server_name'   => array('text' => '服务器名称', 'width' => '160px'),
        	//'server_num'    => array('text' => '服号', 'width' => '160px'),
        	//'develop_id'    => array('text' => '服编号', 'width' => '160px'),
        	'special_name'  => array('text' => '所属专服', 'width' => '160px'),
        	'channel_list'  => array('text' => '渠道列表', 'width' => '200px'),
        	'open_time'     => array('text' => '开服时间', 'width' => '100px'),
            'status_text'   => array('text' => '状态', 'width' => '60px'),
        	'create_user'   => array('text' => '申请人','width' => '80px'),
        	'create_time'   => array('text' => '申请时间','width' => '100px'),
        	'apply_status'  => array('text' => '申请状态','width' => '100px'),
            'action'        => array('text' => '操作', 'width' => '60px'),
        );

        return $header;
    }

    public static function indexData($params){
    	$user = AccAuth::me();
    	if($user['IsAdmin'] != 1){
    		$params['create_user'] = $user['UserID'];
    	}
    	
        $modServerApply = new ModServerApply();
        $result = $modServerApply->page($params);
        
        $modSpecialServer = new ModSpecialServer();
        $specialData = $modSpecialServer->select(array('g'=>$params['g']));
        $specialList = array();
        foreach ($specialData as $key=>$val){
        	$specialList[$val['id']] = $val['name'];
        }
        
        $modChannel = new ModChannel();
        $channelData = $modChannel->select(array('g'=>$params['g']));
        $channelList = array();
        foreach ($channelData as $key=>$val){
        	$channelList[$val['id']] = $val['channel_name'];
        }

       // $statusMap = self::statusList();
        $statusMap = ServerService::checkFlagList();
        $length = count($result['data']);
        $statusList = self::status();
        $userList = self::userList();
        foreach($result['data'] as &$v){
        	$type = 1;
        	if($k == 0 && $length == 1){  //当前页只剩下一条数据时，删除之后需显示上一页的数据
        		$type = 2;
        	}
        	
        	$channel_array = explode(',', $v['channel_list']);
        	$channel_list = '';
        	foreach ($channel_array as $key=>$val){
        		$channel_list .= ','.$channelList[$val];
        	}
        	$channel_list = substr($channel_list, 1);
        	$v['channel_list'] = $channel_list;

        	$v['special_name'] = $specialList[$v['special_id']];
            $v['open_time']     = $v['open_time']? date('Y-m-d H:i:s', $v['open_time']) : '';
            $v['create_time']     = $v['create_time']? date('Y-m-d H:i:s', $v['create_time']) : '';
            $v['status_text']   = $statusMap[$v['status']];
            $v['create_user'] = $userList[$v['create_user']];
            $status = $v['apply_status'];
            if($status == 1){
            	$v['apply_status'] = $statusList[$v['apply_status']];
            }
            if($status == 2){
            	$v['apply_status'] = '<font color="blue">'.$statusList[$v['apply_status']].'</font>';
            	$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
            }
            if($status == 3){
            	$v['apply_status'] = '<font color="red">'.$statusList[$v['apply_status']].'</font>';
            	$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
            }
            
            //$v['action']        .= ' <a href="'.PubFunc::buildBackUrl('/oss/?r=serverApply/edit').'&id='.$v['id'].'">编辑</a>';

            //$v['action']        .= ' <a href="'.PubFunc::buildBackUrl('/oss/?r=serverApply/delete',$type).'&id='.$v['id'].'" confirm="是否要删除该条信息?">删除</a>';            
        }
        unset($v);

        return $result;
    }
    
    public static function approveData($params){
    	$user = AccAuth::me();
    	if($user['IsAdmin'] != 1){
    		$params['create_user'] = $user['UserID'];
    	}
    	 
    	$modServerApply = new ModServerApply();
    	$result = $modServerApply->page($params);
    	
    	$modSpecialServer = new ModSpecialServer();
    	$specialData = $modSpecialServer->select(array('g'=>$params['g']));
    	$specialList = array();
    	foreach ($specialData as $key=>$val){
    		$specialList[$val['id']] = $val['name'];
    	}
    	
    	$modChannel = new ModChannel();
    	$channelData = $modChannel->select(array('g'=>$params['g']));
    	$channelList = array();
    	foreach ($channelData as $key=>$val){
    		$channelList[$val['id']] = $val['channel_name'];
    	}
    	
    	//$statusMap = self::statusList();
    	$statusMap = ServerService::checkFlagList();
    	$length = count($result['data']);
    	$statusList = self::status();
    	$userList = self::userList();
    	foreach($result['data'] as &$v){
    		$type = 1;
    		if($k == 0 && $length == 1){  //当前页只剩下一条数据时，删除之后需显示上一页的数据
    			$type = 2;
    		}
    		 
    		$channel_array = explode(',', $v['channel_list']);
    		$channel_list = '';
    		foreach ($channel_array as $key=>$val){
    			$channel_list .= ','.$channelList[$val];
    		}
    		$channel_list = substr($channel_list, 1);
    		$v['channel_list'] = $channel_list;
    	
    		$v['special_name'] = $specialList[$v['special_id']];
    		$v['open_time']     = $v['open_time']? date('Y-m-d H:i:s', $v['open_time']) : '';
    		$v['create_time']     = $v['create_time']? date('Y-m-d H:i:s', $v['create_time']) : '';
    		$v['status_text']   = $statusMap[$v['status']];
    		$v['create_user'] = $userList[$v['create_user']];
    		
    		$status = $v['apply_status'];
    		if($status == 1){
    			$v['apply_status'] = '<span class="xstatus">'.$statusList[$v['apply_status']].'</span>';
    			$v['action'] .= '<div class="xaction">';
    			$v['action'] .= '<a href="javascript:;" name="approve" data-id="'.$v['id'].'"><font color="blue">批准</font></a>';
    			$v['action'] .= '&nbsp;&nbsp;&nbsp;<a href="javascript:;" name="reject" data-id="'.$v['id'].'"><font color="red">驳回</font></a>';
    			$v['action'] .= '</div>';
    		}
    		if($status == 2){
    			$v['apply_status'] = '<font color="blue">'.$statusList[$v['apply_status']].'</font>';
    			$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
    		}
    		if($status == 3){
    			$v['apply_status'] = '<font color="red">'.$statusList[$v['apply_status']].'</font>';
    			$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
    		}
    	}
    	unset($v);
    	
    	return $result;
    }
    
    public static function doAdd($params){
        $user = AccAuth::me();

        $modServerApply = new ModServerApply();
        
        $channel_array = $params['channel_id'];
        $channel_list = '';
        foreach ($channel_array as $key=>$val){
        	$channel_list .= ','.$val;
        }
        $channel_list = substr($channel_list, 1);

        $modServerApply->platform      = 'test';
        $modServerApply->game          = $params['g'];
        $modServerApply->server_name   = $params['server_name'];
        $modServerApply->server_num    = 0; //废弃
        $modServerApply->open_time     = strtotime($params['open_time']);
        $modServerApply->status        = $params['status'];
        $modServerApply->special_id    = $params['special_id'];
        $modServerApply->channel_list  = $channel_list;
        $modServerApply->create_user   = $user['UserID'];
        $modServerApply->create_time   = time();
        $modServerApply->update_user   = $user['UserID'];
        $modServerApply->update_time   = time();
        $result = $modServerApply->save();
        return $result;
    }

    public static function delete($id){
        if(empty($id)) return false;

        $modServerApply = new ModServerApply();
        $modServerApply->deleteByPk($id);
        return true;
    }
    
    public static function statusList(){
        return array(
            '1'     => '正常',
        	'2'     => '测试',
        );
    }
    
    public static function status(){
    	return array(
    			'1' => '未批准',
    			'2' => '已批准',
    			'3' => '已驳回',
    	);
    }
    
    public static function getApproval($id){
    	$modServerApply = new ModServerApply();
    	$obj = $modServerApply->findByPk($id);
    
    	if($obj){
    		$result = array();
    		$info = $obj->getAttributes();
    		if($info['approval_info'] == ''){
    			return $result;
    		}
    		$approval_info_array = explode(';', $info['approval_info']);
    		$userList = self::userList();
    		foreach ($approval_info_array as $key=>$val){
    			$listOne = json_decode($val,true);
    			$listOne['user'] = $userList[$listOne['user']];
    			$result[] = $listOne;
    		}
    		return $result;
    	}else{
    		return false;
    	}
    }
    
    /**
     * 驳回
     * @param unknown $id
     * @param unknown $status
     * @return multitype:number string
     */
    public static function reject($id){
    	if(empty($id)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}
    
    	$modServerApply = new ModServerApply();
    	$user = AccAuth::me();
    	$obj = $modServerApply->findByPk($id);
    
    	if(!$obj){
    		$result = array('status'=>0,'msg'=>'参数错误','data'=>'');
    		return $result;
    
    	}
    	$info = $obj->getAttributes();
    
    	$approval_info = '驳回';
    	$approval['time'] = date('Y-m-d H:i',time());
    	$approval['user'] = $user['UserID'];
    	$approval['info'] = $approval_info;
    
    	$update = array();
    	$update['apply_status'] = 3;
    	$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    	$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    	$mresult = $modServerApply->updateByPk($id, $update);
    
    	if($mresult){
    		$result = array('status'=>1,'msg'=>'操作成功','data'=>'');
    		return $result;
    	}else{
    		$result = array('status'=>1,'msg'=>'操作失败','data'=>'');
    		return $result;
    	}
    
    }
    
    /**
     * 通知运维
     * @return mixed
     */
    public static function send($info){
    	//查询专服标识
    	$modSpecialServer = new ModSpecialServer();
    	$special = $modSpecialServer->findByPk($info['special_id']);
    	$special_id = $special->getAttributes()['special_id'];
    	//查询渠道标识
    	$channel_list = '';
    	if($info['channel_list'] != ''){
    		$modChannel = new ModChannel();
    		$channelList = $modChannel->getChannelForIds($info['channel_list']);
    		foreach ($channelList as $key=>$val){
    			$channel_list .= ','.$val['tab'];
    		}
    		$channel_list = substr($channel_list, 1);
    	}
    	
    	$data = array();
    	$data['id'] = $info['id'];
    	$data['server_name'] = $info['server_name'];
    	//$data['server_num'] = $info['server_num'];
    	$data['open_time'] = $info['open_time'];
    	$data['special_id'] = $special_id;  
    	$data['channel_list'] = $channel_list;
    	$data['status'] = $info['status'];
    	$message = json_encode($data,JSON_UNESCAPED_UNICODE);
    	
    	$webhook = "https://oapi.dingtalk.com/robot/send?access_token=8c2794ad7467d95350a661f9f58eb88e225433a89e072c4a21c9e01922479fa4";
    	$data = array ('msgtype' => 'text','text' => array ('content' => $message));
    	$data_string = json_encode($data);
    
    	$result = self::request_by_curl($webhook, $data_string); 
    	$result_array = json_decode($result,true);
    	return $result_array;
    }
    
    public static function request_by_curl($remote_server, $post_string) {
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $remote_server);
    	curl_setopt($ch, CURLOPT_POST, 1);
    	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    	curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    	$data = curl_exec($ch);
    	curl_close($ch);
    	 
    	return $data;
    }
    
    
    /**
     * 批准
     */
    public static function approve($id){
    	if(empty($id)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}
    	 
    	$modServerApply = new ModServerApply();
    	$user = AccAuth::me();
    	$obj = $modServerApply->findByPk($id);
    	 
    	if(!$obj){
    		$result = array('status'=>0,'msg'=>'参数错误','data'=>'');
    		return $result;
    		 
    	}
    	$info = $obj->getAttributes();
    	
    	$status = 2;
    	
    	$result_info = self::send($info);
    	if($result_info['errcode'] != 0){ //部分失败或者全部失败
    		$result = array('status'=>0,'msg'=>$result_info['errmsg'],'data'=>'');
    		return $result;
    	}
    	
    	$approval_info = '批准';
    	$approval['time'] = date('Y-m-d H:i',time());
    	$approval['user'] = $user['UserID'];
    	$approval['info'] = $approval_info;
    	 
    	$update = array();
    	$update['apply_status'] = $status;
    	$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    	$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    	$mresult = $modServerApply->updateByPk($id, $update);
    	 
    	if($mresult){
    		$result = array('status'=>1,'msg'=>'操作成功,'.$approval_info,'data'=>$status);
    		return $result;
    	}else{
    		$result = array('status'=>0,'msg'=>'操作失败','data'=>'');
    		return $result;
    	}
    }
    
    public static function get($id){
    	$modServerApply = new ModServerApply();
    	$obj = $modServerApply->findByPk($id);
    
    	if($obj){
    		$info = $obj->getAttributes();
    		$info['open_time']  = empty($info['open_time']) ? '' : date('Y-m-d H:i:s', $info['open_time']);    
    		return $info;
    	}else{
    		return false;
    	}
    }
    
    public static function apply($data){
    	if(empty($data['id'])){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}
    	
    	$user = AccAuth::me();
    	
    	$modServerApply = new ModServerApply();
    	$update = array();
    	$update['server_name']  = $data['server_name'];
    	$update['server_num']   = $data['server_num'];
    	$update['open_time']    = strtotime($data['open_time']);    	
    	$update['status']       = $data['status'];
    	$update['special_id']   = $data['special_id'];
    	$update['channel_list'] = $data['channel_list'];
    	$update['update_user']  = $user['UserID'];
    	$update['update_time']  = time();
    	
    	$result = $modServerApply->updateByPk($data['id'], $update);
    	
    }


    
}